package com.acme.mock;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.exceptions.FeedLoaderException;
import com.acme.bankapp.service.bank.BankDataLoaderService;
import com.acme.bankapp.service.bank.BankService;

public class ConnectionHandler implements Runnable {
	ServerSocket providerSocket;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	Bank bank;

	public ConnectionHandler(Bank b, Socket s) {
		bank = b;
		connection = s;
	}
	
	@Override
	public void run() {
		System.out.println("debur conHandler -  thread start");
		try {
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			in = new ObjectInputStream(connection.getInputStream());
			sendMessage("Connection successful");

			clientInteraction();
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				providerSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	public void clientInteraction() throws IOException {
		do {
			
			try {
				message = (String) in.readObject();
				System.out.println("client>" + message);
				String command[] = message.split(" ",2);
				switch (command[0]) {
				case "add":
					if (command.length == 2){
						if (BankService.addClient(bank, BankDataLoaderService.getClientFromString( command[1] ) ) ){
							sendMessage("Client added");
						}else{
							System.out.println("incorrect parameters or client already exists"); 
						}
					} else {
						sendMessage("unknown command");
					}
					break;
				case "getClients":
					sendMessage( BankReport.getCliensList(bank) );
					break;
				case "bye":
					sendMessage("bye");
					break;
				default:
					sendMessage("unknown command");
					sendMessage("bye");
					break;
				} 
			} catch (ClassNotFoundException classnot) {
				System.err.println("Data received in unknown format");
			} catch (FeedLoaderException feedExc){
				sendMessage(feedExc.getLocalizedMessage());
			}
		
		} while (!message.equals("bye"));
	}

	
	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("server>" + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}
}
